//
//  UserShare.swift
//  RPay
//
//  Created by Charlie Liao on 2017/6/27.
//  Copyright © 2017年 Charlie. All rights reserved.
//

final class UserShare: NSObject {
    
    static let shared = UserShare()
    
    // MARK: - Init
    private override init() {
        super.init()
        loginUser = NSKeyedUnarchiver.unarchiveObject(withFile: userDataPath) as? LoginUser
        reloadShoppingCart()
    }
    
    // MARK: - 登录用户信息
    /// 是否已登录
    var isLogin: Bool {
        return loginUser != nil
    }
    
    /// 登录用户
    var loginUser: LoginUser? {
        didSet {
            saveLoginUser()
            reloadShoppingCart()
        }
    }
    
    /// 登录用户信息存储路径
    private var userDataPath: String {
        return NSString(string: "lu.rpay").inDocumentsDirectoryPath()!
    }
    
    /// 保存登录用户信息
    func saveLoginUser()
    {
        if loginUser != nil {
            let userData = NSKeyedArchiver.archivedData(withRootObject: loginUser!)
            try? userData.write(to: URL(fileURLWithPath: userDataPath))
            
        } else {
            try? FileManager.default.removeItem(atPath: userDataPath)
        }
    }
    
    // MARK: - 购物车信息
    
    private var _shoppingCart: [GoodsModel]?
    /// 购物车列表
    var shoppingCart: [GoodsModel]? {
        return _shoppingCart
    }
    
    /// 添加到购物车
    func addToCart(_ goods: GoodsModel) {
        if _shoppingCart != nil {
            let goodList = _shoppingCart!.filter({ (gds) -> Bool in
                return goods.id == gds.id && goods.name == gds.name && goods.priceStr == gds.priceStr
            })
            
            if goodList.count > 0 { // 购物车已存在该商品
                goodList.first!.num = goodList.first!.num + goods.num
                
            } else { // 购物车未存在该商品
                _shoppingCart!.append(goods.copy() as! GoodsModel)
            }
        }
    }
    
    /// 移出购物车
    func removeFromCart(_ goods: GoodsModel) {
        let goodList = _shoppingCart!.filter({ (gds) -> Bool in
            return goods.id == gds.id && goods.name == gds.name && goods.priceStr == gds.priceStr
        })
        
        for gds in goodList {
            let i = _shoppingCart!.index(of: gds)
            _shoppingCart!.remove(at: i!)
        }
    }
    
    /// 重新加载购物车
    private func reloadShoppingCart() {
        if loginUser == nil {
            _shoppingCart = nil
        } else {
            _shoppingCart = NSKeyedUnarchiver.unarchiveObject(withFile: shoppingCartDataPath) as? [GoodsModel]
            if shoppingCart == nil {
                _shoppingCart = [GoodsModel]()
            }
        }
    }
    
    /// 保存购物车
    func saveShoppingCart() {
        if shoppingCart != nil && loginUser != nil {
            let data = NSKeyedArchiver.archivedData(withRootObject: shoppingCart!)
            try? data.write(to: URL(fileURLWithPath: shoppingCartDataPath))
        }
    }
    
    /// 购物车信息存储路径
    private var shoppingCartDataPath: String {
        let userName = (loginUser!.userName as NSString).md5()!
        return NSString(string: userName.appending("_shct.rpay")).inDocumentsDirectoryPath()!
    }
}

/// 登录用户model
final class LoginUser: NSObject, NSSecureCoding {
    
    init?(content: [String:Any]) {
        
        let userId = content["userId"] as? Int64
        let userName = content["userName"] as? String
        let token = content["token"] as? String
        var rhAccount: Double?
        if let rha = content["rhAccount"] as? String {
            if let rhac = Double(rha) {
                rhAccount = rhac
            }
        }
        
        if userId != nil &&
            userName != nil &&
            token != nil &&
            rhAccount != nil
        {
            self.userId = userId!
            self.userName = userName!
            self.token = token!
            self.rhAccount = rhAccount!
            super.init()
            
        } else {
            fatalError("init(content:) has not been implemented")
        }
    }
    
    init(coder aDecoder: NSCoder) {
        userId = aDecoder.decodeInt64(forKey: "userId")
        userName = aDecoder.decodeObject(forKey: "userName") as! String
        token = aDecoder.decodeObject(forKey: "token") as! String
        rhAccount = aDecoder.decodeDouble(forKey: "rhAccount")
        super.init()
    }
    
    func encode(with aCoder: NSCoder) {
        aCoder.encode(userId, forKey: "userId")
        aCoder.encode(userName, forKey: "userName")
        aCoder.encode(token, forKey: "token")
        aCoder.encode(rhAccount, forKey: "rhAccount")
    }
    
    static var supportsSecureCoding: Bool {
        return true
    }
    
    let userId: Int64
    let userName: String
    let token: String
    
    /// 账户余额
    var rhAccount: Double {
        didSet {
            UserShare.shared.saveLoginUser()
        }
    }
}
